package com.study.common.config;

import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.resources.ConnectionProvider;

import java.time.Duration;

/**
 * WebClient配置
 * - WebClient默认是每个请求创建一个连接,我们可以配置连接池复用连接,以提高性能
 *
 * @author: 王霄
 * @date: 2021/10/12 11:27
 **/
@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient() {
        ConnectionProvider provider = ConnectionProvider.builder("test")
                .maxConnections(100)//允许的最大连接数
                .maxIdleTime(Duration.ofSeconds(30))//连接最大闲置时间
                .pendingAcquireTimeout(Duration.ofMillis(100))//没有连接可用时,请求等待的最长时间
                .build();
        HttpClient httpClient = HttpClient.create(provider)
                .doOnConnected(conn -> conn
                        .addHandlerLast(new ReadTimeoutHandler(10))
                        .addHandlerLast(new WriteTimeoutHandler(10)))
                .responseTimeout(Duration.ofSeconds(15));
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }
}
